<?php
/***
 * Caches any type of content for the amount of time specified in the options.
 * Allows removal of specific items and clearing the whole cache. Also supports
 * changing the cache directory and file extension.
 **/
class Cache {

	/***
	 * $options['directory']
	 *   The directory in which to place the cached files. Remember the
	 *   trailing slash.
	 *   
	 * $options['duration']
	 *   Time in seconds to store a cached file.
	 *      
	 * $options['extension']
	 *   Extension, including the dot, of the cached files.
	 **/
	var $options = array(
		'directory' => 'cache/',
		'duration' => 21600,
		'extension' => '.cache'
	);

	function __construct($options = array()) {
		$this->options = array_merge($this->options, $options);
	}

	function write($name = null, $content = null) {
		$filename = $this->get_filename($name);
		if ($this->deletable($name)) {
			file_put_contents($filename, $content);
			return true;
		}
		return false;
	}
	
	function delete($name = null) {
		$filename = $this->get_filename($name);
		
		if (file_exists($filename)) {
			unlink($filename);
			return true;
		}
		
		return false;
	}
	
	function deletable($name = null) {
		$filename = $this->get_filename($name);
		if (file_exists($filename)) {
			$age = strtotime('now') - filectime($filename);
			if ($age > $this->options['duration']) {
				return true;
			}
		} else {
			return true;
		}
		return false;
	}
	
	function clear() {
		foreach (scandir($this->options['directory']) as $file) {
			if ($file != '.' && $file != '..') {
				unlink($this->get_filename($file, false));
			}
		}
	}
	
	function read($name) {
		return file_get_contents($this->get_filename($name));
	}
	
	private function get_filename($name = null, $extension = true) {
		$filename = implode('', array(
				$this->options['directory'],
				$name,
				($extension ? $this->options['extension'] : '')
			)
		);
		return $filename;
	}

}
?>
